import api from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: null,
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      let user = roles.users[0]
      state.name = user.name
      state.avatar = user.avatar
    },
  },

  actions: {
    // 用户名密码登录
    async login({ commit }, userInfo) {
      userInfo.username = userInfo.username.trim()
      let ret = await api.login(userInfo)
      if (ret.success) {
        setToken(ret.data)
        commit('SET_TOKEN', ret.data)
      }
      return ret
    },

    // 钉钉登录，使用code
    async loginDD({ commit }, { code }) {
      let ret = await api.loginDD({ code })
      if (ret.success) {
        setToken(ret.data)
        commit('SET_TOKEN', ret.data)
      }
      return ret
    },

    // 登出
    async logout({ commit, state }) {
      await api.logout()
      removeToken()
    },

    //获取用户权限
    async getUserInfo({ commit, state }) {
      let ret = await api.getUserInfo()
      if (ret.success) {
        commit('SET_ROLES', ret.data)
      }
      return ret
    },
  }
}

export default user
